<template>
	<dx-layer
		v-model="showModal"
		:title="modalForm.title"
		:mask="mask"
		:maskClosable="maskClosable"
		:showZoom="showZoom"
		:loading="modelLoading"
		:isSync="true"
		:height="height || 680"
		className="dx-layer-form"
		@close="modalClose"
		@cancel="modalClose"
		@confirm="submit"
		ref="dxLayerRef"
	>
		<view class="pt-10px pr-10px">
			<el-form ref="ruleFormRef" :model="layerForm" :rules="layerRules" :label-width="labelWidth || '100px'">
				<template v-for="item in modalForm.fields" :key="item.field">
					<el-form-item :label="item.label" :prop="item.field" v-if="showFormItem(item)">
						<slot :name="`form-${item.field}`" :row="layerForm">
							<dx-layer-form-item :column="item" :formParam="layerForm"></dx-layer-form-item>
						</slot>
					</el-form-item>
				</template>
			</el-form>
		</view>
	</dx-layer>
</template>
<script setup lang="ts" name="DxLayerForm">
import { watch, ref, inject, nextTick } from 'vue';
import { FormInstance } from 'element-plus';
import { useForm } from '../../libs/useForm';
import { provide } from 'vue';
const showModal = ref(false);
// props
const props = withDefaults(
	defineProps<{
		modelValue: boolean;
		modalForm: { [key: string]: any };
		mask?: boolean;
		maskClosable?: boolean;
		showZoom?: boolean;
		labelWidth?: string;
		height?: number;
	}>(),
	{
		mask: true,
		showZoom: true,
	}
);
const dxLayerRef = ref();
const ruleFormRef = ref<FormInstance>();
const onBeforeSubmit: any = inject('onBeforeSubmit', null);
const { layerForm, layerRules, showFormItem, submitForm, modelLoading, setFormItem, setFormField, renderFormValue } = useForm(
	() => {
		dxLayerRef.value?.close();
		close();
	},
	props.modalForm,
	ruleFormRef,
	onBeforeSubmit
);
setFormField(props.modalForm.fields);
// 显示
// 随机数
const dxLayerFormShowId = Math.random().toString(36).substring(2) + Date.now();
// 注入弹窗表单的id
provide('dxLayerFormShowId', dxLayerFormShowId);
// 监听
watch(
	() => props.modelValue,
	(newVal) => {
		if (newVal) {
			showModal.value = true;
			uni.$emit(dxLayerFormShowId);
			renderFormValue();
		}
	}
);
// 绑定关系
const $emit = defineEmits(['update:modelValue', 'close', 'success']);
function modalClose() {
	$emit('update:modelValue', false);
	$emit('close');
}
// 关闭更新
function close() {
	modalClose();
	ruleFormRef.value?.resetFields();
}

// submitForm
function submit() {
	submitForm();
}
// 设置表单字段值

defineExpose({
	setFormItem,
});
</script>
<style lang="scss" scoped>
::v-deep {
	.el-select {
		flex: 1;
	}
}
</style>
